﻿$("document").ready(function () {
    var ViewTabLink = $("#ViewTabLink");
    var SignUpTabLink = $("#SignUpTabLink");
    var ResultMessageModal = $("#ResultMessageModal");
    var ResultMessage = $("#ResultMessage");

    var newsArea = $("#newsArea");
    var signUpForm = $("#SignUpForm");
    var dplProvince = $("#Province");
    var dplCity = $("#City");

    var newsItemForm = $("#NewsItemForm");
    var signUpFormValidator = signUpForm.validate({
        rules: {
            FirstName: {
                required: true,
                minlength: 2,
                maxlength: 20
            },
            LastName: {
                required: true,
                minlength: 2,
                maxlength: 20
            },
            Email: {
                required: true,
                email: true
            },
            Province: "required",
            City: "required"
        },
        messages: {
            FirstName: {
                required: "First name is required",
                minlength: "First name must be between 2 and 20 characters",
                maxlength: "First name must be between 2 and 20 characters"
            },
            LastName: {
                required: "Last name is required",
                minlength: "Last name must be between 2 and 20 characters",
                maxlength: "Last name must be between 2 and 20 characters"
            },
            Email: {
                required: "Email address is required",
                email: "Invalid Email address"
            },
            Province: {
                required:"Please choose a province"
            },
            City: {
                required:"Please choose a city"
            }
        }
    });

    var newsItemFormValidator = newsItemForm.validate({
        rules: {
            Email: {
                required: true,
                email: true,
            },
            Content: {
                required: true,
                minlength: 2,
                maxlength: 500
            }
        },
        messages: {
            Email: {
                required: "Email address is required",
                email: "Invalid Email address"
            },
            Content: {
                required: "News must not be empty",
                minlength: "News content is too short",
                maxlength: "News content must be less than 500 characters"
            }
        }
    });

    var showNews = function () {
        newsArea.empty();
        $.getJSON("api/ViewNews/", function (data) {
            var rows = document.createDocumentFragment();
            $.each(data, function (key, value) {
                var tableRow = $("<tr>");
                tableRow.append($("<td/>").text(value["DateAndTime"]));
                tableRow.append($("<td/>").text(value["Region"]));
                tableRow.append($("<td/>").text(value["Content"]));
                rows.appendChild(tableRow[0]);
            });
            newsArea.append(rows);
        });
    };

    var showSignUpForm = function () {
        dplProvince.empty();
        dplCity.empty();
        dplCity.attr("disabled", true);
        $("#FirstName").val("");
        $("#LastName").val("");
        $("#Email").val("");

        $.getJSON("api/province/", function (data) {
            var options = document.createDocumentFragment();
            options.appendChild($("<option id='ProvincePlaceHoler' value='' >").text("- Please choose -")[0]);
            $.each(data, function (key, value) {
                var option = $("<option>").text(value);
                options.appendChild(option[0]);
            });
            dplProvince.append(options);
        });
    };

    var showCities = function (province) {
        $.getJSON("api/city/", { provinceName: province }, function (data) {
            var options = document.createDocumentFragment();
            options.appendChild($("<option id='CityPlaceHoler' value='' >").text("- Please choose -")[0]);
            $.each(data, function (key, value) {
                var option = $("<option>").text(value);
                options.appendChild(option[0]);
            });
            dplCity.append(options);
        });
    };


    var submitSignUpForm = function (event) {
        var button = $(event.currentTarget);
        button.unbind();
        if (signUpFormValidator.form()) {
            var data = {};
            $("#SignUpForm input").each(function () {
                data[$(this).attr("name")] = $(this).val();
            });
            data["City"] = $("#City").val();

            $.ajax({
                url: "api/CreateNewAccount",
                type: "POST",
                data: JSON.stringify(data),
                contentType: "application/json;charset=utf-8",
                complete: function (xhr) {
                    ResultMessage.text(JSON.parse(xhr.responseText));
                    ResultMessageModal.modal("show");
                    ResultMessageModal.bind("hidden", function dismiss (event) {
                        button.click(submitSignUpForm);
                        ViewTabLink.click();
                        $(event.currentTarget).unbind("hidden", dismiss);
                    });
                }
            });
        }
    };

    var submitNewsItem = function (event) {
        var button = $(event.currentTarget);
        button.unbind();
        if (newsItemFormValidator.form()) {            
            var data = {};
            data[$("#NewsEmail").attr("name")] = $("#NewsEmail").val();
            data[$("#NewsContent").attr("name")] = $("#NewsContent").val();

            $.ajax({
                url: "api/SubmitNews/",
                type: "POST",
                data: JSON.stringify(data),
                contentType: "application/json;charset=utf-8",
                complete: function (xhr) {
                    ResultMessage.text(JSON.parse(xhr.responseText));
                    ResultMessageModal.modal("show");
                    ResultMessageModal.bind("hidden", function dismiss (event) {
                        button.click(submitNewsItem);
                        ViewTabLink.click();
                        $(event.currentTarget).unbind("hidden", dismiss);
                    });
                }
            });
        }
    };

    ViewTabLink.click(function () {
        showNews();
    });

    SignUpTabLink.click(function () {
        signUpFormValidator.resetForm();
        $("#SignUpForm .control-group").removeClass("error");
        showSignUpForm();
    });

    dplProvince.change(function () {
        $("#ProvincePlaceHoler").remove();
        dplCity.empty();
        var province = $(this).val();
        if ("" == province) {
            dplCity.attr("disabled", true);
        } else {
            showCities(province);
            dplCity.removeAttr("disabled");
        }
    });

    dplCity.change(function () {
        $("#CityPlaceHoler").remove();
    });

    $("#Submit").click(submitSignUpForm);

    $("#NewsSubmit").click(submitNewsItem);

    showNews();
});